package com.yq.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName BIOServer
 * @Description BIO实例
 *  *
 * @Author yaoqiang
 * @Date 2021/3/23 14:39
 * @Version 1.0
 * 1、使用BIO模型写一个服务端，监听6666端口
 * 2、使用线程池技术
 * 思路：使用线程池， 建立socket连接,如果有socket连接，就创建线程
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        //创建线程池
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建serverSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("server启动成功");
        while (true){
            //监听等待客户端连接
           final Socket accept = serverSocket.accept();
            System.out.println("有一个客户端连接");
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("等待输入");
                    handler(accept);
                }
            });
        }

    }
    public static void handler(Socket socket) {
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if (read!=-1){
                    System.out.println(new String(bytes,0,read));

                }else {
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
